<?php
/**
 *
 * @author  Devret
 * @mail    461313128@qq.com
 * @create  2020-02-17 1:33
 * https://sixcloud.co/
 * https://gitee.com/devret/AuthorizationSystem.git
 */

//error_reporting(0);
include("./db.class.php");
$type = $_GET['type'];
$data = array(
    "host" => $_GET['host'],        //数据库地址
    "dbname" => $_GET['dbname'],        //数据库名
    "port" => $_GET['port'],
    "user" => $_GET['user'],            //数据库帐号
    "password" => $_GET['password']    //数据库密码
);

$str = '
<?php
$DB=array(
    "host"=>"' . $data['host'] . '",	    //数据库地址
    "dbname"=>"' . $data['dbname'] . '",	//数据库名
    "port"=>"' . $data['port'] . '",        //数据端口
    "user"=>"' . $data['user'] . '",		//数据库帐号
    "password"=>"' . $data['password'] . '"	//数据库密码
);
?>
';
switch ($type) {
    case "a":
        step($str, $data);
        break;
    case "b":
        createDB();
        break;
    case "c":
        //成功不报错误
        createLock();
        //检测其它授权系统数据
        $isOldData = oldDataCheck();
        out(true, "创建lock文件成功!", array("oldData" => $isOldData));
        break;
    case "d":
        oldDataMove();
        break;
}
function out($success, $msg, $object)
{
    die(json_encode(array('success' => $success, 'msg' => $msg, 'data' => $object)));
}

function step($str, $data)
{
    checkDB($data);
    createConfig($str);
}

/**
 * 创建配置文件
 * @param $str
 */
function createConfig($str)
{
    $fp = fopen('../config.php', 'w');
    fwrite($fp, $str);
    out(true, "写入配置文件成功!", $str);
}

/**
 * 检测数据库连接
 */
function checkDB($data)
{
    try {
        $pdo = new PDO("mysql:host=" . $data['host'] . ";port=" . $data['port'] . ";dbname=" . $data['dbname'] . "", $data['user'], $data['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8"));
    } catch (PDOException $e) {
        out(false, "数据库连接失败!", $e->getMessage());
    }
    $pdo = null;
}

/**
 * 创建以及导入数据库表
 */
function createDB()
{
    $sqls = @file_get_contents("install.sql");
    $explode = explode("<sixcloud>", $sqls);
    $sutatData = SQL::exec($explode);
    if (count($sutatData['errorDate']) > 0) {
        out(false, "导入数据表时错误!", $sutatData);
    }
    //创建lock文件
    $isRet = createLock();

    //检测其它授权系统数据
    $isOldData = oldDataCheck();
    out(true, "执行SQL成功!", array("count" => $sutatData['sucCount'], "lock" => $isRet, "oldData" => $isOldData));
}

/**
 * 其它授权系统数据检测
 * @return bool
 */
function oldDataCheck()
{
    $sql = "SELECT 
(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ?  AND TABLE_SCHEMA = ?) as table_km,
(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ?  AND TABLE_SCHEMA = ?) as table_auth";
    $dbName = SQL::getDBName();
    $data = array("auth_kms", $dbName, "openvpn", $dbName);
    $rows = SQL::Read($sql, $data);

    if ($rows[0]['table_km'] != null && $rows[0]['table_auth'] != null) {
        return true;
    } else {
        return false;
    }
}

function oldDataMove()
{
    //迁移卡密
    $sql = "SELECT * FROM `auth_kms` ";
    $oldKmList = SQL::Read($sql, array());
    $bathData = Array();
    $oldKmListLength = count($oldKmList);
    for ($i = 0; $i < $oldKmListLength; $i++) {
        $bathData[$i][0] = "INSERT INTO `sixcloud_kms`(`createuserid`, `card`, `use`,`usedate`, `expiredate`, `createdate`) VALUES (?,?,?,?, ?, ?)";
        $bathData[$i][1] = array(
            1,
            $oldKmList[$i]['km'],
            $oldKmList[$i]['isuse'],
            $oldKmList[$i]['usetime'],
            newAddtime($oldKmList[$i]['addtime'], $oldKmList[$i]['values']),
            $oldKmList[$i]['addtime']);
    }
    $isKm = SQL::batchWrite($bathData);

    //迁移授权帐号
    $sql = "SELECT * FROM `openvpn` ";
    $oldAuthList = SQL::Read($sql, array());
    $bathData = Array();
    $sql = "INSERT INTO `sixcloud_infos`(`authorizer`, `auth`, `key`, `expiredate`, `createdate`, `remark`) VALUES ( ?, ?, ?, ?,?, ?)";
    for ($i = 0; $i < count($oldAuthList); $i++) {
        $bathData[$i][0] = "INSERT INTO `sixcloud_infos`(`authorizer`, `auth`, `key`, `expiredate`, `createdate`, `remark`) VALUES ( ?, ?, ?, ?,?, ?)";
        $bathData[$i][1] = array(
            $oldAuthList[$i]['pass'],
            $oldAuthList[$i]['iuser'],
            $oldAuthList[$i]['endtime'],
            1,
            date("Y-m-d H:i:s", $oldAuthList[$i]['starttime']),
            "来源于数据迁移");
    }
    $isAuth = SQL::batchWrite($bathData);
    out($isKm && $isAuth, $isKm && $isAuth ? "数据迁移成功！" : "数据迁移失败！", array("km" => $isKm, "auth" => $isAuth));
}

/*
 * 计算新到期时间
 */
function newAddtime($odlAddtime, $day)
{
    if ($day != 0) {
        $new = date("Y-m-d H:i:s", strtotime("+" . $day . " day", strtotime($odlAddtime)));
        return $new;
    } else {
        return 1;
    }
}

/**
 * 创建lock文件
 * @return bool|int
 */
function createLock()
{
    $isRet = file_put_contents('six_install.lock', '6云互联-专业的主机供应商https://sixcloud.co/');
    if ($isRet != false) {
        $isRet = true;
    } else {
        out($isRet, "创建lock文件失败,请重试!", null);
    }
    return $isRet;
}